package com.weiya.system.error;

import com.google.gson.Gson;
import com.weiya.response.ResponseVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p class="detail">
 * 功能:自定义全局异常统一处理
 * </p>
 *
 * @author BaoWeiwei
 * @ClassName System global exception resolver.
 * @Version V1.0.
 * @date 2018.08.10 11:01:28
 */
//@Component
public class SystemGlobalExceptionResolver implements HandlerExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(SystemGlobalExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) {
        try {
            PrintWriter printWriter = response.getWriter();

            //返回结果封装类
            ResponseVo resultJson = new ResponseVo();
            //业务异常的时候，按照各业务自身的异常消息进行返回
            if (ex instanceof CustomException) {
                resultJson.setCode(((CustomException) ex).getCode());
                resultJson.setMsg(ex.getMessage());
            } else {//非业务异常的时候，统一处理为系统异常消息进行返回
                resultJson.setCode(500);
                logger.error("系统异常，请稍后尝试！", ex);
                resultJson.setMsg("系统异常，请稍后尝试！");
            }

            Gson gson = new Gson();
            String json = gson.toJson(resultJson);
            logger.error("全局异常处理！返回结果：{}", json, ex);
            response.setContentType("application/json;charset=UTF-8");
            //返回json数据。
            printWriter.println(json);
            printWriter.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}
